package com.zx.framework.web.message;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.lang.reflect.Type;
import java.nio.charset.Charset;

import org.apache.log4j.Logger;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.AbstractHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.StreamUtils;

import com.google.gson.Gson;
import com.google.gson.JsonParseException;
import com.google.gson.reflect.TypeToken;
import com.zx.framework.core.util.gson.GsonUtil;
/**
 * 使用gosn处理@responseBody注解,用于json和对象的转换
 * @author stylewolf
 * 2014-04-17
 */
public class GSONHttpMessageConverter extends AbstractHttpMessageConverter<Object>{
	
	private static final Logger LOGGER = Logger.getLogger(GSONHttpMessageConverter.class);
	
	public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
	
	public GSONHttpMessageConverter() {
        super(new MediaType("application", "json", DEFAULT_CHARSET));
    }
	@Override
	protected Object readInternal(Class<? extends Object> clazz,
			HttpInputMessage inputMessage) throws IOException,
			HttpMessageNotReadableException {
		try {
            Gson gson = GsonUtil.getGsonBuidler().create();
            return gson.fromJson(StreamUtils.copyToString(inputMessage.getBody(), DEFAULT_CHARSET),clazz);
        } catch (JsonParseException e) {
            throw new HttpMessageNotReadableException("Could not read JSON: " + e.getMessage(), e);
        }
	}

	@Override
	protected boolean supports(Class<?> arg0) {
		return true;
	}

	@Override
	protected void writeInternal(Object arg0, HttpOutputMessage outputMessage)
			throws IOException, HttpMessageNotWritableException {
		Type genericType = TypeToken.get(arg0.getClass()).getType();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputMessage.getBody(), DEFAULT_CHARSET));
        try {
        	if(arg0 instanceof String){
        		writer.append((String)arg0);
        	}else{
        		// See http://code.google.com/p/google-gson/issues/detail?id=199 for details on SQLTimestamp conversion
        		Gson gson = GsonUtil.getGsonBuidler().create();
                writer.append(gson.toJson(arg0, genericType));
        	}
        } finally {
            writer.flush();
            writer.close();
        }
	}
}
